import React, { Component } from "react";

class Box extends Component {
    //使用scu函数进行性能优化
    shouldComponentUpdate(nextProps, nextState) {
        //当新的props属性中number和isShow相等时，边框需要变红，允许重新渲染
        //当老的props属性中number和isShow相等时，边框可能需要从红色变回黑色，允许重新渲染
        //其它情况阻止渲染，提高性能
        if (
            this.props.number === this.props.isShow ||
            nextProps.number === nextProps.isShow
        ) {
            return true;
        }
        return false;
    }
    render() {
        console.log("Box组件重新渲染");
        return (
            <div
                style={{
                    width: "100px",
                    height: "100px",
                    border:
                        this.props.number === this.props.isShow
                            ? "5px solid red"
                            : "1px solid black",
                    float: "left",
                    margin: "20px",
                }}>
                {this.props.number}
            </div>
        );
    }
}
export default class App extends Component {
    state = {
        list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        isShow: 0,
    };
    render() {
        return (
            <div>
                <input
                    type='number'
                    onChange={(e) => {
                        this.setState({
                            isShow: Number(e.target.value),
                        });
                    }}
                    value={this.state.isShow}
                />
                {/* overflow: "hidden"清除浮动 */}
                <div style={{ overflow: "hidden" }}>
                    {this.state.list.map((item) => (
                        <Box
                            key={item}
                            number={item}
                            isShow={this.state.isShow}></Box>
                    ))}
                </div>
            </div>
        );
    }
}
